home *** CD-ROM | disk | FTP | other *** search
/ PCGUIA 117 / PC Guia 117.iso / Software / Produtividade / Software2 / Product4 / Setup.exe / drupal-4.6.0 / includes / xmlrpc.inc < prev    next >
Encoding:
Text File  |  2005-03-31  |  30.1 KB  |  1,096 lines

  1. <?php
  2. // by Edd Dumbill (C) 1999-2001
  3. // <edd@usefulinc.com>
  4. // $Id: xmlrpc.inc,v 1.16 2005/03/31 21:18:08 dries Exp $
  5.  
  6.  
  7. // Copyright (c) 1999,2000,2001 Edd Dumbill.
  8. // All rights reserved.
  9. //
  10. // Redistribution and use in source and binary forms, with or without
  11. // modification, are permitted provided that the following conditions
  12. // are met:
  13. //
  14. //    * Redistributions of source code must retain the above copyright
  15. //      notice, this list of conditions and the following disclaimer.
  16. //
  17. //    * Redistributions in binary form must reproduce the above
  18. //      copyright notice, this list of conditions and the following
  19. //      disclaimer in the documentation and/or other materials provided
  20. //      with the distribution.
  21. //
  22. //    * Neither the name of the "XML-RPC for PHP" nor the names of its
  23. //      contributors may be used to endorse or promote products derived
  24. //      from this software without specific prior written permission.
  25. //
  26. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  27. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  28. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  29. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  30. // REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  31. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  32. // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  33. // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  34. // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  35. // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  36. // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  37. // OF THE POSSIBILITY OF SUCH DAMAGE.
  38.  
  39. if (!function_exists('xml_parser_create')) {
  40.   dl("xml.so");
  41. }
  42.  
  43. $xmlrpcI4="i4";
  44. $xmlrpcInt="int";
  45. $xmlrpcBoolean="boolean";
  46. $xmlrpcDouble="double";
  47. $xmlrpcString="string";
  48. $xmlrpcDateTime="dateTime.iso8601";
  49. $xmlrpcBase64="base64";
  50. $xmlrpcArray="array";
  51. $xmlrpcStruct="struct";
  52.  
  53.  
  54. $xmlrpcTypes=array($xmlrpcI4 => 1,
  55.     $xmlrpcInt => 1,
  56.     $xmlrpcBoolean => 1,
  57.     $xmlrpcString => 1,
  58.     $xmlrpcDouble => 1,
  59.     $xmlrpcDateTime => 1,
  60.     $xmlrpcBase64 => 1,
  61.     $xmlrpcArray => 2,
  62.     $xmlrpcStruct => 3);
  63.  
  64. $xmlEntities=array(   "amp" => "&",
  65.     "quot" => '"',
  66.     "lt" => "<",
  67.     "gt" => ">",
  68.     "apos" => "'");
  69.  
  70. $xmlrpcerr["unknown_method"]=1;
  71. $xmlrpcstr["unknown_method"]="Unknown method";
  72. $xmlrpcerr["invalid_return"]=2;
  73. $xmlrpcstr["invalid_return"]="Invalid return payload: enabling debugging to examine incoming payload";
  74. $xmlrpcerr["incorrect_params"]=3;
  75. $xmlrpcstr["incorrect_params"]="Incorrect parameters passed to method";
  76. $xmlrpcerr["introspect_unknown"]=4;
  77. $xmlrpcstr["introspect_unknown"]="Can't introspect: method unknown";
  78. $xmlrpcerr["http_error"]=5;
  79. $xmlrpcstr["http_error"]="Didn't receive 200 OK from remote server.";
  80. $xmlrpcerr["no_data"]=6;
  81. $xmlrpcstr["no_data"]="No data received from server.";
  82. $xmlrpcerr["no_ssl"]=7;
  83. $xmlrpcstr["no_ssl"]="No SSL support compiled in.";
  84. $xmlrpcerr["curl_fail"]=8;
  85. $xmlrpcstr["curl_fail"]="CURL error";
  86.  
  87. $xmlrpcName="XML-RPC for PHP";
  88. $xmlrpcVersion="1.02";
  89.  
  90. // let user errors start at 800
  91. $xmlrpcerruser=800;
  92. // let XML parse errors start at 100
  93. $xmlrpcerrxml=100;
  94.  
  95. // formulate backslashes for escaping regexp
  96. $xmlrpc_backslash=chr(92).chr(92);
  97.  
  98. // used to store state during parsing
  99. // quick explanation of components:
  100. //   st - used to build up a string for evaluation
  101. //   ac - used to accumulate values
  102. //   qt - used to decide if quotes are needed for evaluation
  103. //   cm - used to denote struct or array (comma needed)
  104. //   isf - used to indicate a fault
  105. //   lv - used to indicate "looking for a value": implements
  106. //        the logic to allow values with no types to be strings
  107. //   params - used to store parameters in method calls
  108. //   method - used to store method name
  109.  
  110. $_xh=array();
  111.  
  112. function xmlrpc_entity_decode($string) {
  113.   $top=split("&", $string);
  114.   $op="";
  115.   $i=0;
  116.   while($i<sizeof($top)) {
  117.     if (ereg("^([#a-zA-Z0-9]+);", $top[$i], $regs)) {
  118.       $op.=ereg_replace("^[#a-zA-Z0-9]+;",
  119.           xmlrpc_lookup_entity($regs[1]),
  120.           $top[$i]);
  121.     } else {
  122.       if ($i==0)
  123.         $op=$top[$i];
  124.       else
  125.         $op.="&" . $top[$i];
  126.     }
  127.     $i++;
  128.   }
  129.   return $op;
  130. }
  131.  
  132. function xmlrpc_lookup_entity($ent) {
  133.   global $xmlEntities;
  134.  
  135.   if (isset($xmlEntities[strtolower($ent)]))
  136.     return $xmlEntities[strtolower($ent)];
  137.   if (ereg("^#([0-9]+)$", $ent, $regs))
  138.     return chr($regs[1]);
  139.   return "?";
  140. }
  141.  
  142. function xmlrpc_se($parser, $name, $attrs) {
  143.   global $_xh, $xmlrpcDateTime, $xmlrpcString;
  144.  
  145.   switch($name) {
  146.     case "STRUCT":
  147.       case "ARRAY":
  148.       $_xh[$parser]['st'].="array(";
  149.     $_xh[$parser]['cm']++;
  150.     // this last line turns quoting off
  151.     // this means if we get an empty array we'll
  152.     // simply get a bit of whitespace in the eval
  153.     $_xh[$parser]['qt']=0;
  154.     break;
  155.     case "NAME":
  156.       $_xh[$parser]['st'].="'"; $_xh[$parser]['ac']="";
  157.     break;
  158.     case "FAULT":
  159.       $_xh[$parser]['isf']=1;
  160.     break;
  161.     case "PARAM":
  162.       $_xh[$parser]['st']="";
  163.     break;
  164.     case "VALUE":
  165.       $_xh[$parser]['st'].="new xmlrpcval(";
  166.     $_xh[$parser]['vt']=$xmlrpcString;
  167.     $_xh[$parser]['ac']="";
  168.     $_xh[$parser]['qt']=0;
  169.     $_xh[$parser]['lv']=1;
  170.     // look for a value: if this is still 1 by the
  171.     // time we reach the first data segment then the type is string
  172.     // by implication and we need to add in a quote
  173.     break;
  174.  
  175.     case "I4":
  176.       case "INT":
  177.       case "STRING":
  178.       case "BOOLEAN":
  179.       case "DOUBLE":
  180.       case "DATETIME.ISO8601":
  181.       case "BASE64":
  182.       $_xh[$parser]['ac']=""; // reset the accumulator
  183.  
  184.     if ($name=="DATETIME.ISO8601" || $name=="STRING") {
  185.       $_xh[$parser]['qt']=1;
  186.       if ($name=="DATETIME.ISO8601")
  187.         $_xh[$parser]['vt']=$xmlrpcDateTime;
  188.     } else if ($name=="BASE64") {
  189.       $_xh[$parser]['qt']=2;
  190.     } else {
  191.       // No quoting is required here -- but
  192.       // at the end of the element we must check
  193.       // for data format errors.
  194.       $_xh[$parser]['qt']=0;
  195.     }
  196.     break;
  197.     case "MEMBER":
  198.       $_xh[$parser]['ac']="";
  199.     break;
  200.     default:
  201.     break;
  202.   }
  203.  
  204.   if ($name!="VALUE") $_xh[$parser]['lv']=0;
  205. }
  206.  
  207. function xmlrpc_ee($parser, $name) {
  208.   global $_xh,$xmlrpcTypes,$xmlrpcString;
  209.  
  210.   switch($name) {
  211.     case "STRUCT":
  212.       case "ARRAY":
  213.       if ($_xh[$parser]['cm'] && substr($_xh[$parser]['st'], -1) ==',') {
  214.         $_xh[$parser]['st']=substr($_xh[$parser]['st'],0,-1);
  215.       }
  216.     $_xh[$parser]['st'].=")";
  217.     $_xh[$parser]['vt']=strtolower($name);
  218.     $_xh[$parser]['cm']--;
  219.     break;
  220.     case "NAME":
  221.       $_xh[$parser]['st'].= $_xh[$parser]['ac'] . "' => ";
  222.     break;
  223.     case "BOOLEAN":
  224.       // special case here: we translate boolean 1 or 0 into PHP
  225.       // constants true or false
  226.       if ($_xh[$parser]['ac']=='1')
  227.         $_xh[$parser]['ac']="true";
  228.       else
  229.         $_xh[$parser]['ac']="false";
  230.     $_xh[$parser]['vt']=strtolower($name);
  231.     // Drop through intentionally.
  232.     case "I4":
  233.       case "INT":
  234.       case "STRING":
  235.       case "DOUBLE":
  236.       case "DATETIME.ISO8601":
  237.       case "BASE64":
  238.       if ($_xh[$parser]['qt']==1) {
  239.         // we use double quotes rather than single so backslashification works OK
  240.         $_xh[$parser]['st'].="\"". $_xh[$parser]['ac'] . "\"";
  241.       } else if ($_xh[$parser]['qt']==2) {
  242.         $_xh[$parser]['st'].="base64_decode('". $_xh[$parser]['ac'] . "')";
  243.       } else if ($name=="BOOLEAN") {
  244.         $_xh[$parser]['st'].=$_xh[$parser]['ac'];
  245.       } else {
  246.         // we have an I4, INT or a DOUBLE
  247.         // we must check that only 0123456789-.<space> are characters here
  248.         if (!ereg("^\-?[0123456789 \t\.]+$", $_xh[$parser]['ac'])) {
  249.           // TODO: find a better way of throwing an error
  250.           // than this!
  251.           error_log("XML-RPC: non numeric value received in INT or DOUBLE");
  252.           $_xh[$parser]['st'].="ERROR_NON_NUMERIC_FOUND";
  253.         } else {
  254.           // it's ok, add it on
  255.           $_xh[$parser]['st'].=$_xh[$parser]['ac'];
  256.         }
  257.       }
  258.     $_xh[$parser]['ac']=""; $_xh[$parser]['qt']=0;
  259.     $_xh[$parser]['lv']=3; // indicate we've found a value
  260.     break;
  261.     case "VALUE":
  262.       // deal with a string value
  263.       if (strlen($_xh[$parser]['ac'])>0 &&
  264.           $_xh[$parser]['vt']==$xmlrpcString) {
  265.         $_xh[$parser]['st'].="\"". $_xh[$parser]['ac'] . "\"";
  266.       }
  267.     // This if() detects if no scalar was inside <VALUE></VALUE>
  268.     // and pads an empty "".
  269.     if($_xh[$parser]['st'][strlen($_xh[$parser]['st'])-1] == '(') {
  270.       $_xh[$parser]['st'].= '""';
  271.     }
  272.     $_xh[$parser]['st'].=", '" . $_xh[$parser]['vt'] . "')";
  273.     if ($_xh[$parser]['cm']) $_xh[$parser]['st'].=",";
  274.     break;
  275.     case "MEMBER":
  276.       $_xh[$parser]['ac']=""; $_xh[$parser]['qt']=0;
  277.     break;
  278.     case "DATA":
  279.       $_xh[$parser]['ac']=""; $_xh[$parser]['qt']=0;
  280.     break;
  281.     case "PARAM":
  282.       $_xh[$parser]['params'][]=$_xh[$parser]['st'];
  283.     break;
  284.     case "METHODNAME":
  285.       $_xh[$parser]['method']=ereg_replace("^[\n\r\t ]+", "",
  286.           $_xh[$parser]['ac']);
  287.     break;
  288.     case "BOOLEAN":
  289.       // special case here: we translate boolean 1 or 0 into PHP
  290.       // constants true or false
  291.       if ($_xh[$parser]['ac']=='1')
  292.         $_xh[$parser]['ac']="true";
  293.       else
  294.         $_xh[$parser]['ac']="false";
  295.     $_xh[$parser]['vt']=strtolower($name);
  296.     break;
  297.     default:
  298.     break;
  299.   }
  300.   // if it's a valid type name, set the type
  301.   if (isset($xmlrpcTypes[strtolower($name)])) {
  302.     $_xh[$parser]['vt']=strtolower($name);
  303.   }
  304.  
  305. }
  306.  
  307. function xmlrpc_cd($parser, $data)
  308. {
  309.   global $_xh, $xmlrpc_backslash;
  310.  
  311.   //if (ereg("^[\n\r \t]+$", $data)) return;
  312.   // print "adding [${data}]\n";
  313.  
  314.   if ($_xh[$parser]['lv']!=3) {
  315.     // "lookforvalue==3" means that we've found an entire value
  316.     // and should discard any further character data
  317.     if ($_xh[$parser]['lv']==1) {
  318.       // if we've found text and we're just in a <value> then
  319.       // turn quoting on, as this will be a string
  320.       $_xh[$parser]['qt']=1;
  321.       // and say we've found a value
  322.       $_xh[$parser]['lv']=2;
  323.     }
  324.     // replace characters that eval would
  325.     // do special things with
  326.     $_xh[$parser]['ac'].=str_replace('$', '\$',
  327.         str_replace('"', '\"', str_replace(chr(92),
  328.             $xmlrpc_backslash, $data)));
  329.   }
  330. }
  331.  
  332. function xmlrpc_dh($parser, $data)
  333. {
  334.   global $_xh;
  335.   if (substr($data, 0, 1) == "&" && substr($data, -1, 1) == ";") {
  336.     if ($_xh[$parser]['lv']==1) {
  337.       $_xh[$parser]['qt']=1;
  338.       $_xh[$parser]['lv']=2;
  339.     }
  340.     $_xh[$parser]['ac'].=str_replace('$', '\$',
  341.         str_replace('"', '\"', str_replace(chr(92),
  342.             $xmlrpc_backslash, $data)));
  343.   }
  344. }
  345.  
  346. class xmlrpc_client {
  347.   var $path;
  348.   var $server;
  349.   var $port;
  350.   var $errno;
  351.   var $errstring;
  352.   var $debug=0;
  353.   var $username="";
  354.   var $password="";
  355.   var $cert="";
  356.   var $certpass="";
  357.  
  358.   function xmlrpc_client($path, $server, $port=0) {
  359.     $this->port=$port; $this->server=$server; $this->path=$path;
  360.   }
  361.  
  362.   function setDebug($in) {
  363.     if ($in) {
  364.       $this->debug=1;
  365.     } else {
  366.       $this->debug=0;
  367.     }
  368.   }
  369.  
  370.   function setCredentials($u, $p) {
  371.     $this->username=$u;
  372.     $this->password=$p;
  373.   }
  374.  
  375.   function setCertificate($cert, $certpass) {
  376.     $this->cert = $cert;
  377.     $this->certpass = $certpass;
  378.   }
  379.  
  380.   function send($msg, $timeout=0, $method='http') {
  381.     // where msg is an xmlrpcmsg
  382.     $msg->debug=$this->debug;
  383.  
  384.     if ($method == 'https') {
  385.       return $this->sendPayloadHTTPS($msg,
  386.           $this->server,
  387.           $this->port, $timeout,
  388.           $this->username, $this->password,
  389.           $this->cert,
  390.           $this->certpass);
  391.     } else {
  392.       return $this->sendPayloadHTTP10($msg, $this->server, $this->port,
  393.           $timeout, $this->username,
  394.           $this->password);
  395.     }
  396.   }
  397.  
  398.   function sendPayloadHTTP10($msg, $server, $port, $timeout=0,
  399.       $username="", $password="") {
  400.     if ($port==0) $port=80;
  401.     if($timeout>0)
  402.       $fp=fsockopen($server, $port,
  403.           $this->errno, $this->errstr, $timeout);
  404.     else
  405.       $fp=fsockopen($server, $port,
  406.           $this->errno, $this->errstr);
  407.     if (!$fp) {
  408.       return 0;
  409.     }
  410.     // Only create the payload if it was not created previously
  411.     if(empty($msg->payload)) $msg->createPayload();
  412.  
  413.     // thanks to Grant Rauscher <grant7@firstworld.net>
  414.     // for this
  415.     $credentials="";
  416.     if ($username!="") {
  417.       $credentials="Authorization: Basic " .
  418.         base64_encode($username . ":" . $password) . "\r\n";
  419.     }
  420.  
  421.     $op= "POST " . $this->path. " HTTP/1.0\r\nUser-Agent: PHP XMLRPC 1.0\r\n" .
  422.       "Host: ". $this->server  . "\r\n" .
  423.       $credentials .
  424.       "Content-Type: text/xml\r\nContent-Length: " .
  425.       strlen($msg->payload) . "\r\n\r\n" .
  426.       $msg->payload;
  427.  
  428.     if (!fputs($fp, $op, strlen($op))) {
  429.       $this->errstr="Write error";
  430.       return 0;
  431.     }
  432.     $resp=$msg->parseResponseFile($fp);
  433.     fclose($fp);
  434.     return $resp;
  435.   }
  436.  
  437.   // contributed by Justin Miller <justin@voxel.net>
  438.   // requires curl to be built into PHP
  439.   function sendPayloadHTTPS($msg, $server, $port, $timeout=0,
  440.       $username="", $password="", $cert="",
  441.       $certpass="") {
  442.     global $xmlrpcerr, $xmlrpcstr;
  443.     if ($port == 0) $port = 443;
  444.  
  445.     // Only create the payload if it was not created previously
  446.     if(empty($msg->payload)) $msg->createPayload();
  447.  
  448.     if (!function_exists("curl_init")) {
  449.       $r=new xmlrpcresp(0, $xmlrpcerr["no_ssl"],
  450.           $xmlrpcstr["no_ssl"]);
  451.       return $r;
  452.     }
  453.  
  454.     $curl = curl_init("https://" . $server . ':' . $port .
  455.         $this->path);
  456.  
  457.     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  458.     // results into variable
  459.     if ($this->debug) {
  460.       curl_setopt($curl, CURLOPT_VERBOSE, 1);
  461.     }
  462.     curl_setopt($curl, CURLOPT_USERAGENT, 'PHP XMLRPC 1.0');
  463.     // required for XMLRPC
  464.     curl_setopt($curl, CURLOPT_POST, 1);
  465.     // post the data
  466.     curl_setopt($curl, CURLOPT_POSTFIELDS, $msg->payload);
  467.     // the data
  468.     curl_setopt($curl, CURLOPT_HEADER, 1);
  469.     // return the header too
  470.     curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
  471.     // required for XMLRPC
  472.     if ($timeout) curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 :
  473.         $timeout - 1);
  474.     // timeout is borked
  475.     if ($username && $password) curl_setopt($curl, CURLOPT_USERPWD,
  476.         "$username:$password");
  477.     // set auth stuff
  478.     if ($cert) curl_setopt($curl, CURLOPT_SSLCERT, $cert);
  479.     // set cert file
  480.     if ($certpass) curl_setopt($curl, CURLOPT_SSLCERTPASSWD,
  481.         $certpass);
  482.     // set cert password
  483.  
  484.     $result = curl_exec($curl);
  485.  
  486.     if (!$result) {
  487.       $resp=new xmlrpcresp(0,
  488.           $xmlrpcerr["curl_fail"],
  489.           $xmlrpcstr["curl_fail"]. ": ".
  490.           curl_error($curl));
  491.     } else {
  492.       $resp = $msg->parseResponse($result);
  493.     }
  494.     curl_close($curl);
  495.     return $resp;
  496.   }
  497.  
  498. } // end class xmlrpc_client
  499.  
  500. class xmlrpcresp {
  501.   var $xv;
  502.   var $fn;
  503.   var $fs;
  504.   var $hdrs;
  505.  
  506.   function xmlrpcresp($val, $fcode=0, $fstr="") {
  507.     if ($fcode!=0) {
  508.       $this->xv=0;
  509.       $this->fn=$fcode;
  510.       $this->fs=htmlspecialchars($fstr);
  511.     } else {
  512.       $this->xv=$val;
  513.       $this->fn=0;
  514.     }
  515.   }
  516.  
  517.   function faultCode() {
  518.     if (isset($this->fn))
  519.       return $this->fn;
  520.     else
  521.       return 0;
  522.   }
  523.  
  524.   function faultString() { return $this->fs; }
  525.   function value() { return $this->xv; }
  526.  
  527.   function serialize() {
  528.     $rs="<methodResponse>\n";
  529.     if ($this->fn) {
  530.       $rs.="<fault>
  531.         <value>
  532.         <struct>
  533.         <member>
  534.         <name>faultCode</name>
  535.         <value><int>" . $this->fn . "</int></value>
  536.         </member>
  537.         <member>
  538.         <name>faultString</name>
  539.         <value><string>" . $this->fs . "</string></value>
  540.         </member>
  541.         </struct>
  542.         </value>
  543.         </fault>";
  544.     } else {
  545.       $rs.="<params>\n<param>\n" . $this->xv->serialize() .
  546.         "</param>\n</params>";
  547.     }
  548.     $rs.="\n</methodResponse>";
  549.     return $rs;
  550.   }
  551. }
  552.  
  553. class xmlrpcmsg {
  554.   var $payload;
  555.   var $methodname;
  556.   var $params=array();
  557.   var $debug=0;
  558.  
  559.   function xmlrpcmsg($meth, $pars=0) {
  560.     $this->methodname=$meth;
  561.     if (is_array($pars) && sizeof($pars)>0) {
  562.       for($i=0; $i<sizeof($pars); $i++)
  563.         $this->addParam($pars[$i]);
  564.     }
  565.   }
  566.  
  567.   function xml_header() {
  568.     return "<?xml version=\"1.0\"?>\n<methodCall>\n";
  569.   }
  570.  
  571.   function xml_footer() {
  572.     return "</methodCall>\n";
  573.   }
  574.  
  575.   function createPayload() {
  576.     $this->payload=$this->xml_header();
  577.     $this->payload.="<methodName>" . $this->methodname . "</methodName>\n";
  578.     //  if (sizeof($this->params)) {
  579.     $this->payload.="<params>\n";
  580.     for($i=0; $i<sizeof($this->params); $i++) {
  581.       $p=$this->params[$i];
  582.       $this->payload.="<param>\n" . $p->serialize() .
  583.         "</param>\n";
  584.     }
  585.     $this->payload.="</params>\n";
  586.     // }
  587.     $this->payload.=$this->xml_footer();
  588.     $this->payload=str_replace("\n", "\r\n", $this->payload);
  589.   }
  590.  
  591.   function method($meth="") {
  592.     if ($meth!="") {
  593.       $this->methodname=$meth;
  594.     }
  595.     return $this->methodname;
  596.   }
  597.  
  598.   function serialize() {
  599.     $this->createPayload();
  600.     return $this->payload;
  601.   }
  602.  
  603.   function addParam($par) { $this->params[]=$par; }
  604.   function getParam($i) { return $this->params[$i]; }
  605.   function getNumParams() { return sizeof($this->params); }
  606.  
  607.   function parseResponseFile($fp) {
  608.     $ipd="";
  609.  
  610.     while($data=fread($fp, 32768)) {
  611.       $ipd.=$data;
  612.     }
  613.     return $this->parseResponse($ipd);
  614.   }
  615.  
  616.   function parseResponse($data="") {
  617.     global $_xh,$xmlrpcerr,$xmlrpcstr;
  618.  
  619.  
  620.     $xmlparser = drupal_xml_parser_create($data);
  621.     $parser = (int)$xmlparser;
  622.  
  623.     $_xh[$parser]=array();
  624.  
  625.     $_xh[$parser]['st']="";
  626.     $_xh[$parser]['cm']=0;
  627.     $_xh[$parser]['isf']=0;
  628.     $_xh[$parser]['ac']="";
  629.     $_xh[$parser]['qt']="";
  630.     $_xh[$parser]['ha']="";
  631.     $_xh[$parser]['ac']="";
  632.  
  633.     xml_parser_set_option($xmlparser, XML_OPTION_CASE_FOLDING, true);
  634.     xml_set_element_handler($xmlparser, "xmlrpc_se", "xmlrpc_ee");
  635.     xml_set_character_data_handler($xmlparser, "xmlrpc_cd");
  636.     xml_set_default_handler($xmlparser, "xmlrpc_dh");
  637.     $xmlrpc_value=new xmlrpcval;
  638.  
  639.     if ($this->debug)
  640. ##print "<pre>---GOT---\n" . htmlspecialchars($data) .  "\n---END---\n</pre>";
  641. ##print "<p>---GOT---\n" . nl2br(htmlspecialchars($data)) .  "\n---END---\n</p>";
  642.       print "<p>---GOT---\n" . nl2br($data) .  "\n---END---\n</p>";
  643.     if ($data=="") {
  644.       error_log("No response received from server.");
  645.       $r=new xmlrpcresp(0, $xmlrpcerr["no_data"],
  646.           $xmlrpcstr["no_data"]);
  647.       xml_parser_free($xmlparser);
  648.       return $r;
  649.     }
  650.     // see if we got an HTTP 200 OK, else bomb
  651.     // but only do this if we're using the HTTP protocol.
  652.     if (ereg("^HTTP",$data) &&
  653.         !ereg("^HTTP/[0-9\.]+ 200 ", $data)) {
  654.       $errstr= substr($data, 0, strpos($data, "\n")-1);
  655.       error_log("HTTP error, got response: " .$errstr);
  656.       $r=new xmlrpcresp(0, $xmlrpcerr["http_error"],
  657.           $xmlrpcstr["http_error"]. " (" . $errstr . ")");
  658.       xml_parser_free($xmlparser);
  659.       return $r;
  660.     }
  661.  
  662.     // if using HTTP, then gotta get rid of HTTP headers here
  663.     // and we store them in the 'ha' bit of our data array
  664.     if (ereg("^HTTP", $data)) {
  665.       $ar=explode("\r\n", $data);
  666.       $newdata="";
  667.       $hdrfnd=0;
  668.       for ($i=0; $i<sizeof($ar); $i++) {
  669.         if (!$hdrfnd) {
  670.           if (strlen($ar[$i])>0) {
  671.             $_xh[$parser]['ha'].=$ar[$i]. "\r\n";
  672.           } else {
  673.             $hdrfnd=1;
  674.           }
  675.         } else {
  676.           $newdata.=$ar[$i] . "\r\n";
  677.         }
  678.       }
  679.       $data=$newdata;
  680.     }
  681.  
  682.     if (!xml_parse($xmlparser, $data, sizeof($data))) {
  683.       // thanks to Peter Kocks <peter.kocks@baygate.com>
  684.       if((xml_get_current_line_number($xmlparser)) == 1)
  685.         $errstr = "XML error at line 1, check URL";
  686.       else
  687.         $errstr = sprintf("XML error: %s at line %d",
  688.             xml_error_string(xml_get_error_code($xmlparser)),
  689.             xml_get_current_line_number($xmlparser));
  690.       error_log($errstr);
  691.       $r=new xmlrpcresp(0, $xmlrpcerr["invalid_return"],
  692.           $xmlrpcstr["invalid_return"]);
  693.       xml_parser_free($xmlparser);
  694.       return $r;
  695.     }
  696.     xml_parser_free($xmlparser);
  697.     if ($this->debug) {
  698.       print "<pre>---EVALING---[" .
  699.         strlen($_xh[$parser]['st']) . " chars]---\n" .
  700.         htmlspecialchars($_xh[$parser]['st']) . ";\n---END---</pre>";
  701.     }
  702.     if (strlen($_xh[$parser]['st'])==0) {
  703.       // then something odd has happened
  704.       // and it's time to generate a client side error
  705.       // indicating something odd went on
  706.       $r=new xmlrpcresp(0, $xmlrpcerr["invalid_return"],
  707.           $xmlrpcstr["invalid_return"]);
  708.     } else {
  709.       eval('$v=' . $_xh[$parser]['st'] . '; $allOK=1;');
  710.       if ($_xh[$parser]['isf']) {
  711.         $f=$v->structmem("faultCode");
  712.         $fs=$v->structmem("faultString");
  713.         $r=new xmlrpcresp($v, $f->scalarval(),
  714.             $fs->scalarval());
  715.       } else {
  716.         $r=new xmlrpcresp($v);
  717.       }
  718.     }
  719.     $r->hdrs=split("\r?\n", $_xh[$parser]['ha']);
  720.     return $r;
  721.   }
  722.  
  723. }
  724.  
  725. class xmlrpcval {
  726.   var $me=array();
  727.   var $mytype=0;
  728.  
  729.   function xmlrpcval($val=-1, $type="") {
  730.     global $xmlrpcTypes;
  731.     $this->me=array();
  732.     $this->mytype=0;
  733.     if ($val!=-1 || $type!="") {
  734.       if ($type=="") $type="string";
  735.       if ($xmlrpcTypes[$type]==1) {
  736.         $this->addScalar($val,$type);
  737.       }
  738.       else if ($xmlrpcTypes[$type]==2)
  739.         $this->addArray($val);
  740.       else if ($xmlrpcTypes[$type]==3)
  741.         $this->addStruct($val);
  742.     }
  743.   }
  744.  
  745.   function addScalar($val, $type="string") {
  746.     global $xmlrpcTypes, $xmlrpcBoolean;
  747.  
  748.     if ($this->mytype==1) {
  749.       echo "<strong>xmlrpcval</strong>: scalar can have only one value<br />";
  750.       return 0;
  751.     }
  752.     $typeof=$xmlrpcTypes[$type];
  753.     if ($typeof!=1) {
  754.       echo "<strong>xmlrpcval</strong>: not a scalar type (${typeof})<br />";
  755.       return 0;
  756.     }
  757.  
  758.     if ($type==$xmlrpcBoolean) {
  759.       if (strcasecmp($val,"true")==0 ||
  760.           $val==1 || ($val==true &&
  761.             strcasecmp($val,"false"))) {
  762.         $val=1;
  763.       } else {
  764.         $val=0;
  765.       }
  766.     }
  767.  
  768.     if ($this->mytype==2) {
  769.       // we're adding to an array here
  770.       $ar=$this->me["array"];
  771.       $ar[]=new xmlrpcval($val, $type);
  772.       $this->me["array"]=$ar;
  773.     } else {
  774.       // a scalar, so set the value and remember we're scalar
  775.       $this->me[$type]=$val;
  776.       $this->mytype=$typeof;
  777.     }
  778.     return 1;
  779.   }
  780.  
  781.   function addArray($vals) {
  782.     global $xmlrpcTypes;
  783.     if ($this->mytype!=0) {
  784.       echo "<strong>xmlrpcval</strong>: already initialized as a [" .
  785.         $this->kindOf() . "]<br />";
  786.       return 0;
  787.     }
  788.  
  789.     $this->mytype=$xmlrpcTypes["array"];
  790.     $this->me["array"]=$vals;
  791.     return 1;
  792.   }
  793.  
  794.   function addStruct($vals) {
  795.     global $xmlrpcTypes;
  796.     if ($this->mytype!=0) {
  797.       echo "<strong>xmlrpcval</strong>: already initialized as a [" .
  798.         $this->kindOf() . "]<br />";
  799.       return 0;
  800.     }
  801.     $this->mytype=$xmlrpcTypes["struct"];
  802.     $this->me["struct"]=$vals;
  803.     return 1;
  804.   }
  805.  
  806.   function dump($ar) {
  807.     reset($ar);
  808.     while ( list( $key, $val ) = each( $ar ) ) {
  809.       echo "$key => $val<br />";
  810.       if ($key == 'array')
  811.         while ( list( $key2, $val2 ) = each( $val ) ) {
  812.           echo "-- $key2 => $val2<br />";
  813.         }
  814.     }
  815.   }
  816.  
  817.   function kindOf() {
  818.     switch($this->mytype) {
  819.       case 3:
  820.         return "struct";
  821.         break;
  822.       case 2:
  823.         return "array";
  824.         break;
  825.       case 1:
  826.         return "scalar";
  827.         break;
  828.       default:
  829.         return "undef";
  830.     }
  831.   }
  832.  
  833.   function serializedata($typ, $val) {
  834.     $rs="";
  835.     global $xmlrpcTypes, $xmlrpcBase64, $xmlrpcString,
  836.     $xmlrpcBoolean;
  837.     switch($xmlrpcTypes[$typ]) {
  838.       case 3:
  839.         // struct
  840.         $rs.="<struct>\n";
  841.         reset($val);
  842.         while(list($key2, $val2)=each($val)) {
  843.           $rs.="<member><name>${key2}</name>\n";
  844.           $rs.=$this->serializeval($val2);
  845.           $rs.="</member>\n";
  846.         }
  847.         $rs.="</struct>";
  848.         break;
  849.       case 2:
  850.         // array
  851.         $rs.="<array>\n<data>\n";
  852.         for($i=0; $i<sizeof($val); $i++) {
  853.           $rs.=$this->serializeval($val[$i]);
  854.         }
  855.         $rs.="</data>\n</array>";
  856.         break;
  857.       case 1:
  858.         switch ($typ) {
  859.           case $xmlrpcBase64:
  860.             $rs.="<${typ}>" . base64_encode($val) . "</${typ}>";
  861.             break;
  862.           case $xmlrpcBoolean:
  863.             $rs.="<${typ}>" . ($val ? "1" : "0") . "</${typ}>";
  864.             break;
  865.           case $xmlrpcString:
  866.             $rs.="<${typ}>" . htmlspecialchars($val). "</${typ}>";
  867.             break;
  868.           default:
  869.             $rs.="<${typ}>${val}</${typ}>";
  870.         }
  871.         break;
  872.       default:
  873.         break;
  874.     }
  875.     return $rs;
  876.   }
  877.  
  878.   function serialize() {
  879.     return $this->serializeval($this);
  880.   }
  881.  
  882.   function serializeval($o) {
  883.     global $xmlrpcTypes;
  884.     $rs="";
  885.     $ar=$o->me;
  886.     reset($ar);
  887.     list($typ, $val) = each($ar);
  888.     $rs.="<value>";
  889.     $rs.=$this->serializedata($typ, $val);
  890.     $rs.="</value>\n";
  891.     return $rs;
  892.   }
  893.  
  894.   function structmem($m) {
  895.     $nv=$this->me["struct"][$m];
  896.     return $nv;
  897.   }
  898.  
  899.   function structreset() {
  900.     reset($this->me["struct"]);
  901.   }
  902.  
  903.   function structeach() {
  904.     return each($this->me["struct"]);
  905.   }
  906.  
  907.   function getval() {
  908.     // UNSTABLE
  909.     global $xmlrpcBoolean, $xmlrpcBase64;
  910.     reset($this->me);
  911.     list($a,$b)=each($this->me);
  912.     // contributed by I Sofer, 2001-03-24
  913.     // add support for nested arrays to scalarval
  914.     // I've created a new method here, so as to
  915.     // preserve back compatibility
  916.  
  917.     if (is_array($b))    {
  918.       foreach ($b as $id => $cont) {
  919.         $b[$id] = $cont->scalarval();
  920.       }
  921.     }
  922.  
  923.     // add support for structures directly encoding php objects
  924.     if (is_object($b))  {
  925.       $t = get_object_vars($b);
  926.       foreach ($t as $id => $cont) {
  927.         $t[$id] = $cont->scalarval();
  928.       }
  929.       foreach ($t as $id => $cont) {
  930.         eval('$b->'.$id.' = $cont;');
  931.       }
  932.     }
  933.     // end contrib
  934.     return $b;
  935.   }
  936.  
  937.   function scalarval() {
  938.     global $xmlrpcBoolean, $xmlrpcBase64;
  939.     reset($this->me);
  940.     list($a,$b)=each($this->me);
  941.     return $b;
  942.   }
  943.  
  944.   function scalartyp() {
  945.     global $xmlrpcI4, $xmlrpcInt;
  946.     reset($this->me);
  947.     list($a,$b)=each($this->me);
  948.     if ($a==$xmlrpcI4)
  949.       $a=$xmlrpcInt;
  950.     return $a;
  951.   }
  952.  
  953.   function arraymem($m) {
  954.     $nv=$this->me["array"][$m];
  955.     return $nv;
  956.   }
  957.  
  958.   function arraysize() {
  959.     reset($this->me);
  960.     list($a,$b)=each($this->me);
  961.     return sizeof($b);
  962.   }
  963. }
  964.  
  965. // date helpers
  966. function iso8601_encode($timet, $utc=0) {
  967.   // return an ISO8601 encoded string
  968.   // really, timezones ought to be supported
  969.   // but the XML-RPC spec says:
  970.   //
  971.   // "Don't assume a timezone. It should be specified by the server in its
  972.   // documentation what assumptions it makes about timezones."
  973.   //
  974.   // these routines always assume localtime unless
  975.   // $utc is set to 1, in which case UTC is assumed
  976.   // and an adjustment for locale is made when encoding
  977.   if (!$utc) {
  978.     $t=strftime("%Y%m%dT%H:%M:%S", $timet);
  979.   } else {
  980.     if (function_exists("gmstrftime"))
  981.       // gmstrftime doesn't exist in some versions
  982.       // of PHP
  983.       $t=gmstrftime("%Y%m%dT%H:%M:%S", $timet);
  984.     else {
  985.       $t=strftime("%Y%m%dT%H:%M:%S", $timet-date("Z"));
  986.     }
  987.   }
  988.   return $t;
  989. }
  990.  
  991. function iso8601_decode($idate, $utc=0) {
  992.   // return a timet in the localtime, or UTC
  993.   $t=0;
  994.   if (ereg("([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})",
  995.         $idate, $regs)) {
  996.     if ($utc) {
  997.       $t=gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
  998.     } else {
  999.       $t=mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
  1000.     }
  1001.   }
  1002.   return $t;
  1003. }
  1004.  
  1005. /*****************************************************************
  1006.  * _xmlrpc_decode takes a message in PHP xmlrpc object format and *
  1007.  * translates it into native PHP types.                            *
  1008.  *                                                                *
  1009.  * author: Dan Libby (dan@libby.com)                              *
  1010.  *****************************************************************/
  1011. function _xmlrpc_decode($xmlrpc_val) {
  1012.   $kind = $xmlrpc_val->kindOf();
  1013.  
  1014.   if($kind == "scalar") {
  1015.     return $xmlrpc_val->scalarval();
  1016.   }
  1017.   else if($kind == "array") {
  1018.     $size = $xmlrpc_val->arraysize();
  1019.     $arr = array();
  1020.  
  1021.     for($i = 0; $i < $size; $i++) {
  1022.       $arr[]=_xmlrpc_decode($xmlrpc_val->arraymem($i));
  1023.     }
  1024.     return $arr;
  1025.   }
  1026.   else if($kind == "struct") {
  1027.     $xmlrpc_val->structreset();
  1028.     $arr = array();
  1029.  
  1030.     while(list($key,$value)=$xmlrpc_val->structeach()) {
  1031.       $arr[$key] = _xmlrpc_decode($value);
  1032.     }
  1033.     return $arr;
  1034.   }
  1035. }
  1036.  
  1037. /****************************************************************
  1038.  * _xmlrpc_encode takes native php types and encodes them into   *
  1039.  * xmlrpc PHP object format.                                     *
  1040.  * BUG: All sequential arrays are turned into structs.  I don't  *
  1041.  * know of a good way to determine if an array is sequential     *
  1042.  * only.                                                         *
  1043.  *                                                               *
  1044.  * feature creep -- could support more types via optional type   *
  1045.  * argument.                                                     *
  1046.  *                                                               *
  1047.  * author: Dan Libby (dan@libby.com)                             *
  1048.  ****************************************************************/
  1049. function _xmlrpc_encode($php_val) {
  1050.   global $xmlrpcInt;
  1051.   global $xmlrpcDouble;
  1052.   global $xmlrpcString;
  1053.   global $xmlrpcArray;
  1054.   global $xmlrpcStruct;
  1055.   global $xmlrpcBoolean;
  1056.  
  1057.   $type = gettype($php_val);
  1058.   $xmlrpc_val = new xmlrpcval;
  1059.  
  1060.   switch($type) {
  1061.     case "array":
  1062.       case "object":
  1063.       $arr = array();
  1064.     while (list($k,$v) = each($php_val)) {
  1065.       $arr[$k] = _xmlrpc_encode($v);
  1066.     }
  1067.     $xmlrpc_val->addStruct($arr);
  1068.     break;
  1069.     case "integer":
  1070.       $xmlrpc_val->addScalar($php_val, $xmlrpcInt);
  1071.     break;
  1072.     case "double":
  1073.       $xmlrpc_val->addScalar($php_val, $xmlrpcDouble);
  1074.     break;
  1075.     case "string":
  1076.       $xmlrpc_val->addScalar($php_val, $xmlrpcString);
  1077.     break;
  1078.     // <G_Giunta_2001-02-29>
  1079.     // Add support for encoding/decoding of booleans, since they are supported in PHP
  1080.     case "boolean":
  1081.       $xmlrpc_val->addScalar($php_val, $xmlrpcBoolean);
  1082.     break;
  1083.     // </G_Giunta_2001-02-29>
  1084.     case "unknown type":
  1085.     default:
  1086.       // giancarlo pinerolo <ping@alt.it>
  1087.       // it has to return
  1088.       // an empty object in case (which is already
  1089.       // at this point), not a boolean.
  1090.       break;
  1091.   }
  1092.   return $xmlrpc_val;
  1093. }
  1094.  
  1095. ?>
  1096.